import React, { Component} from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card,Button,Form,Row,Col,Radio,message } from 'antd';
import PropTypes from 'prop-types';
import { FormInstance } from 'antd/lib/form';
import SingleSpecification from './singleSpecification';
import { routerRedux } from 'dva/router';

const FormItem = Form.Item;
@connect((state: any) => ({
  menu: state.menu,
  goodEdit: state.goodEdit,
}))
class salesInfo extends Component<any, any> {
  formRef = React.createRef<FormInstance>();
  static contextTypes = {
    dicData: PropTypes.any,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      goodsSpecFlag: 1,//商品规格
    };
  }
  singleRef = React.createRef();
  componentDidMount() {
    this.props.onRef(this);
    if(sessionStorage.getItem('goodsaleInfo')){
      const saleInfo = JSON.parse(sessionStorage.getItem('goodsaleInfo') || '{}');
      this.setState({
        goodsSpecFlag: saleInfo.goodsSpecFlag,
      })
      this.formRef.current?.setFieldsValue(saleInfo);
    }else{
      this.formRef.current?.resetFields;
    }
  }
  ok=()=>{

  }
  preStep = async () => {
    await this.saveValue();
    this.props.preStep();
  }
  saveValue = async () => {
   const singleInfo = await this.singleRef.formRef?.current?.validateFields().then((values:any) => {
     return values;
    })
    const values = await this.formRef.current?.getFieldsValue(true);
    const TableData = await this.singleRef.getTableData();
    let params = {};
    if(values.goodsSpecFlag === 1){
     params = {
      ...singleInfo,
      ...values,
      attributeList: TableData,
    }
    }else if(values.goodsSpecFlag === 2){
      params = {
        ...values,
      }
    }
    await sessionStorage.setItem('goodsaleInfo', JSON.stringify(params));
   }
   save= async () => {
    await this.saveValue();
    const basicInfo = JSON.parse(sessionStorage.getItem('goodBasicInfo') || '{}');
    const singleInfo = await this.singleRef.formRef?.current?.validateFields().then((values:any) => {
      return values;
     })
     const values = await this.formRef.current?.getFieldsValue(true);
     const TableData = await this.singleRef.getTableData();
     const sid = JSON.parse(sessionStorage.getItem('updateGoodId') || '{}');
     let  ifErr = false;//数据是否正常标志，默认为正常
     for (var i = 0; i < TableData.length; i++) {
      var item = TableData[i];
      if(!item.skuAttributeName || item.skuAttributeName == null){
        const i = item.key +1;
        message.warning('请填写完整第'+i+'项的数据！');
        ifErr = true;
       }
       if (item.skuAttributeName && (!item.skuAttributeValue || item.skuAttributeValue == '' || item.skuAttributeValue === null)) {
         message.warning('请填写'+item.skuAttributeName+'的附属属性值！');
         ifErr = true;
         // return;
       }
       } 
     if (ifErr) {
       return;
     }
     if(basicInfo.goodsMaxPrice){
      const maxPrice = parseFloat(basicInfo.goodsMaxPrice);
      const goodsPrice = parseFloat(singleInfo.goodsPrice);
      if(maxPrice  && maxPrice < goodsPrice) {
        message.warning('商品价格不得超过商品最高总价！');
        return;
      }
      if(singleInfo.discountPrice){
       const discountPrice = parseFloat(singleInfo.discountPrice);
       if(maxPrice  && maxPrice < discountPrice) {
         message.warning('商品折扣价不得超过商品最高总价！');
         return;
       }
      }
     }
     const params = {
      ...basicInfo,
      ...singleInfo,
      ...values,
      sid: sid,
      carTypes: basicInfo.carTypes?.toString(),
      goodsPlatform: basicInfo.goodsPlatform.toString(),
      goodsAttachment:basicInfo.fileList&& basicInfo.fileList.length > 0   ?  basicInfo.fileList[0].response.data.fileUrl : '',
      skuVo:[{attributeInputMethod: singleInfo.attributeInputMethod, goodsPrice: singleInfo.goodsPrice, discountPrice: singleInfo.discountPrice, attributeList: TableData}],
     }
     delete params['attributeList'];
     delete params['goodsPrice'];
     delete params['discountPrice'];
     delete params['attributeInputMethod'];
     this.props.dispatch({
      type: 'goodAdd/postObjWithRes',
      payload: {url:'/optshop/base/goods/update', ...params },
      callback: (response:any) => {
        if(response.statusCode == '0'){
          sessionStorage.removeItem('goodBasicInfo');
          sessionStorage.removeItem('goodsaleInfo');
          const { dispatch } = this.props;
        dispatch(routerRedux.push({ pathname: '/goodsManager/goodsMng', sourcePage: 'goodsMng' }));
        }
      },
    });
   }
  onChange =(val:any)=>{
   this.setState({
    goodsSpecFlag : val.target.value,
   })
  }
  render() {
    const {goodsSpecFlag}=this.state;
    const {attributeList} =this.props;
    return (
      <Card>
        <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.ok} 
        initialValues={{
          goodsSpecFlag: 1,
        }}>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
               label="商品规格"
               name="goodsSpecFlag"
               rules={[{ required: true, message: '请选择商品规格' }]}
              >
                <Radio.Group name="radiogroup" onChange={this.onChange}>
                     <Radio value={1}>单规格</Radio>
                     <Radio value={2} disabled>多规格</Radio>
                </Radio.Group>
              </FormItem>
          </Col>
          </Row>
          {goodsSpecFlag === 1 && (
          <SingleSpecification
          onRef={(singleRef:any) => (this.singleRef = singleRef)}
          attributeList={attributeList}/>
          )}
        </Form>
        <div style={{float:'right'}}>
        <Button onClick={()=>{this.preStep()}}>上一步</Button>
        <Button type="primary" style={{marginLeft: '8px'}} onClick={()=>{this.save()}}>保存</Button>
        </div>
      </Card>
    );
  }
}

export default salesInfo;
